<template>
  <div class="user-container">
    <!-- 搜索表单 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.id"
            placeholder="请输入用户ID"
            clearable
            size="small"
            @clear="handleSearch"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="昵称">
          <el-input
            v-model="searchForm.nickname"
            placeholder="请输入昵称"
            clearable
            size="small"
            @clear="handleSearch"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.mobile"
            placeholder="邮箱"
            clearable
            size="small"
            @keyup.enter.native="handleSearch"
            @clear="handleSearch"
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small"
            >搜索</el-button
          >
          <el-button @click="resetSearch" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <div class="table-section">
      <el-table :data="userList" stripe border>
        <el-table-column label="头像" width="120" align="center">
          <template slot-scope="scope">
            <div class="avatar-container">
              <img
                v-if="scope.row.avatar"
                :src="scope.row.avatar"
                class="avatar-img"
              />
              <i v-else class="el-icon-user-solid avatar-icon"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDisabled ? 'danger' : 'success'">
              {{ scope.row.isDisabled ? "禁用" : "正常" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="showUserDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.isDisabled ? "启用" : "禁用" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10]"
          layout="total, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      :visible="detailVisible"
      @close="detailVisible = false"
      width="600px"
    >
      <div class="detail-container">
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">用户ID：</el-col>
          <el-col :span="18">{{ currentUser.id }}</el-col>
        </el-row>
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">昵称：</el-col>
          <el-col :span="18">{{ currentUser.nickname }}</el-col>
        </el-row>
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">邮箱：</el-col>
          <el-col :span="18">{{ currentUser.email }}</el-col>
        </el-row>
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">性别：</el-col>
          <el-col :span="18">{{ formatGender(currentUser.sex) }}</el-col>
        </el-row>
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">年龄：</el-col>
          <el-col :span="18">{{ currentUser.age }}</el-col>
        </el-row>
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">注册时间：</el-col>
          <el-col :span="18">{{
            formatDate(null, null, currentUser.gmtCreate)
          }}</el-col>
        </el-row>
        <el-row class="detail-row">
          <el-col :span="6" class="detail-label">状态：</el-col>
          <el-col :span="18">
            <el-tag :type="currentUser.isDisabled ? 'danger' : 'success'">
              {{currentUser.isDisabled ? "禁用" : "正常"}}
            </el-tag>
          </el-col>
        </el-row>
      </div>
      <div slot="footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/acl/user";

export default {
  data() {
    return {
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      detailVisible: false,
      currentUser: {},
      searchForm: {
        id: "",
        nickname: "",
        mobile: "",
      },
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    formatDate(row, column, cellValue) {
      if (!cellValue) return "";
      try {
        return new Date(cellValue).toLocaleString();
      } catch (e) {
        return cellValue;
      }
    },

    formatGender(gender) {
      switch (gender) {
        case 1:
          return "女";
        case 2:
          return "男";
        default:
          return "未知";
      }
    },

    // 显示用户详情
    showUserDetail(user) {
      console.log("用户数据:", user);
      this.currentUser = { ...user };
      this.detailVisible = true;
    },

    // 获取用户列表
    getUserList() {
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        ...this.searchForm,
      };

      userApi
        .getUserList(params)
        .then((response) => {
          console.log("完整响应:", response);
          this.userList = response.data.items || [];
          this.total = response.data.total || 0;
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("获取用户列表失败");
        });
    },

    // 搜索用户
    handleSearch() {
      this.currentPage = 1;
      this.getUserList();
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        id: "",
        nickname: "",
        mobile: "",
      };
      this.handleSearch();
    },

    // 分页变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getUserList();
    },

    // 切换用户状态
    handleToggleStatus(user) {
      const action = user.isDisabled ? "启用" : "禁用";
      this.$confirm(`确定要${action}该用户吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          userApi
            .toggleUserStatus(user.id)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success(`${action}成功`);
                // 直接取反本地状态
                user.isDisabled = !user.isDisabled;
              } else {
                this.$message.error(response.message);
              }
            })
            .catch((error) => {
              console.error(error);
              this.$message.error(`${action}失败`);
            });
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
  },
};
</script>

<style scoped>
.user-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-form .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

.table-section {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.el-avatar {
  background-color: #f5f7fa;
}

.detail-container {
  padding: 10px;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.header-meta {
  margin-left: 20px;
}

.header-meta h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.el-divider {
  margin: 16px 0;
}

.detail-container {
  padding: 20px;
}

.el-divider {
  margin: 20px 0;
  background-color: #f0f0f0;
}

.detail-row {
  margin: 12px 0;
  line-height: 32px;
}
.detail-label {
  color: #888;
  text-align: right;
  padding-right: 15px;
}

.avatar-container {
  display: inline-block;
  text-align: center;
}
.avatar-img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}
.avatar-icon {
  font-size: 50px;
  color: #c0c4cc;
  background: #f5f7fa;
  border-radius: 50%;
  padding: 10px;
}
</style>